<template>
  <div>
    <el-form
      ref="addFormRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="果园名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入果园名称" />
      </el-form-item>
      <el-form-item label="果园封面图" prop="avatar">
        <UploadImg v-model="formData.avatar" :limit="1" :is-show-tip="false" />
      </el-form-item>
      <el-form-item label="供货分类" prop="cateIds">
        <el-select v-model="formData.cateIds" multiple placeholder="请选择分类">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id" />         
        </el-select>
      </el-form-item>
      <el-form-item label="联系人" prop="contacts">
        <el-input v-model="formData.contacts" placeholder="请输入联系人名称" />
      </el-form-item>
      <el-form-item label="联系号码" prop="phone">
        <el-input type="number" v-model="formData.phone" :maxlength="11" placeholder="请输入联系号码" />
      </el-form-item>
      <el-form-item label="联系人微信号" prop="wxAccount">
        <el-input v-model="formData.wxAccount" placeholder="请输入微信号" />
      </el-form-item>
      <el-form-item label="所在地" prop="location">
        <el-cascader
          v-model="formData.location"
          :props="defaultAddressProps"
          :options="addressList" />         
      </el-form-item>
      <el-form-item label="详细地址" prop="address">
        <el-input
          type="textarea"
          :rows="2"
          maxlength="140"
          show-word-limit
          placeholder="请输入详细地址"
          v-model="formData.address" />
      </el-form-item>
      <el-form-item label="推广码" prop="code">
        <el-input v-model="formData.code" placeholder="请输入推广码" />
      </el-form-item>      
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          :rows="2"
          maxlength="140"
          show-word-limit
          placeholder="请输入说明备注"
          v-model="formData.remark" />
      </el-form-item>
      <el-form-item label="果园状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value" >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否直营" prop="selfOrchard">
        <el-radio-group v-model="formData.selfOrchard">
          <el-radio :label="true" >是 </el-radio>
          <el-radio :label="false" > 否 </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="cancelForm">取 消</el-button>
      </el-form-item>
    </el-form>   
  </div>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import * as ProductCategoryApi from '@/api/mall/product/category'
import * as OrchardApi from '@/api/mall/orchard/orchard'
import { defaultAddressProps } from '@/utils/tree'
import addressList from '@/api/data/index.json'

defineOptions({ name: 'AddOrchardForm' })

const props = defineProps({orchardId: {type: Number}})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: '',
  avatar: '',
  status: CommonStatusEnum.ENABLE,
  wxAccount:'',
  phone:'',
  contacts:'',
  address:'',
  cateIds:[],
  location:[],
  province:'',
  city:'',
  area:'',
  code:'',
  remark: '',
  selfOrchard: false
})
const formRules = reactive({
  name: [{ required: true, message: '果园名称不能为空', trigger: 'blur' }],
  phone: [{ required: true, message: '联系号码不能为空', trigger: 'blur' },
  { min: 11, max: 11, message: '手机号格式不正确', trigger: 'blur' }
  ],
  contacts: [{ required: true, message: '联系人名称不能为空', trigger: 'blur' }],
  address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
  location: [{ required: true, message: '果园所在地不能为空', trigger: 'blur' }],
  wxAccount: [{ required: true, message: '微信号不能为空', trigger: 'blur' }],
  cateIds: [{ required: true, message: '请选择分类', trigger: 'blur' }]
})
const addFormRef = ref() // 表单 Ref

const categoryList = ref<CategoryVO[]>([]) // 商品分类树
/** 打开弹窗 */

defineExpose({formData})

/** 提交表单 */
const emit = defineEmits(['cancelFormHandle']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!addFormRef) return
  const valid = await addFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    data.province = data.location[0]
    data.city = data.location[1]
    data.area = data.location[2]
    if (data.id == null || data.id == undefined) {
      await OrchardApi.addOrchard(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrchardApi.editOrchard(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('cancelFormHandle')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    avatar: '',
    status: CommonStatusEnum.ENABLE,
    wxAccount:'',
    phone:'',
    contacts:'',
    address:'',
    cateIds:[],
    location:[],
    province:'',
    city:'',
    area:'',
    code:'',
    remark: '',
    selfOrchard: false
  }
  addFormRef.value?.resetFields()
}
const cancelForm = () => {
  emit('cancelFormHandle')
}

onMounted(async () => {
  // 获得分类
  const data = await ProductCategoryApi.getTopCategoryList()
  categoryList.value = data
  if(props.orchardId != null && props.orchardId != undefined && props.orchardId > 0) {
    const data = await OrchardApi.getDetail({id: props.orchardId})
    let location = []
    location.push(data.province)
    location.push(data.city)
    location.push(data.area)
    formData.value = {
      id: data.id,
      name: data.name,
      avatar: data.avatar,
      status: data.status,
      wxAccount: data.wxAccount,
      phone: data.phone,
      contacts: data.contacts,
      address: data.address,
      cateIds: data.cateIds,
      location: location,
      province: '',
      city:'',
      area:'',
      code: data.code,
      remark: data.remark,
      selfOrchard: data.selfOrchard
    }
  }
})
</script>

<style lang="scss" scoped>
 :deep(.el-input) {
    width: 40%;
  }
  :deep(.el-select) {
    width: 40%;
  }
  :deep(.el-textarea) {
    width: 40%;
  }
  :deep(.el-cascader) {
    width: 100%;
  }
</style>
